<?php

namespace App\Exports;

use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\FromCollection;

class AllExport implements FromCollection
{
    // 传进来的数据体
    private $data;
    // 表名
    private $tableName;
    // excel列名
    private $head;

    public function __construct($data,$tableName,$head)
    {
        $this->data = $data;
        $this->tableName = $tableName;
        $this->head = $head;
    }

    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        // 如果没有传递列名 或者列名为空则用表结构导出
        if(!$this->head){
            $prefix = DB::connection()->getTablePrefix();
            $field = DB::select("desc ".$prefix.$this->tableName);
            $data = [];
            foreach($field as $value){
                $data[0][] = $value->Field;
            }
            $res = $data;
        }else{
            $res = [$this->head];
        }
        $res = array_merge($res,$this->data);

        return collect($res);
    }
}
